package com.youmingxing.adpter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.youmingxing.R;
import com.youmingxing.adpter.RecyclerViewAdapter.HomeTemplate1Adapter;
import com.youmingxing.adpter.RecyclerViewAdapter.HomeTemplate3Adapter;
import com.youmingxing.adpter.RecyclerViewAdapter.HomeTemplate4Adapter;
import com.youmingxing.bean.Section;
import com.youmingxing.bean.SectionContent;
import com.youmingxing.utils.DisplayUtil;
import com.youmingxing.utils.ListViewHightEvent;
import com.youmingxing.utils.LogUtil;
import com.youmingxing.utils.ViewHolderUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.net.URL;
import java.util.List;


/**
 * @author evilyin(ChenZhixi)
 * @since 15/11/21
 */
public class MovieListAdapter extends BaseAdapter {

    private Context context;
    private List<Section> sectionList;
    private ImageLoader imageLoader;

    public MovieListAdapter(Context context, List<Section> list) {
        this.context = context;
        this.sectionList = list;
        imageLoader = ImageLoader.getInstance();
    }

    @Override
    public int getCount() {
        return sectionList.size();
    }

    @Override
    public Object getItem(int position) {
        return sectionList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        return sectionList.get(position).template;
    }

    @Override
    public int getViewTypeCount() {
        return 5;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final Section section = sectionList.get(position);
        if (convertView == null) {
            switch (section.template) {
                case 1:
                case 3:
                    convertView = View.inflate(context, R.layout.item_template_1and3_horizontal, null);
                    break;
                case 2:
                    convertView = View.inflate(context, R.layout.item_template_2_events, null);
                    break;
                case 4:
                    convertView = View.inflate(context, R.layout.item_template_4_rank, null);
                    break;
            }
        }
        TextView title = ViewHolderUtils.getViewHolderView(convertView, R.id.title_template);
        TextView more = ViewHolderUtils.getViewHolderView(convertView, R.id.see_more);
        title.setText(section.title);
        if (section.more) {
            more.setText(section.more_tip);
            more.setVisibility(View.VISIBLE);
            more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    section.more_action.jump(context);
                }
            });
        } else {
            more.setVisibility(View.GONE);
        }
        //横向布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

        switch (section.template) {
            case 1:
                RecyclerView horizontalView = ViewHolderUtils.getViewHolderView
                        (convertView, R.id.recyclerview_horizontal);
                horizontalView.setLayoutManager(linearLayoutManager);
                //设置适配器
                HomeTemplate1Adapter mAdapter = new HomeTemplate1Adapter(context,
                        section.sectionContentList);
                horizontalView.setAdapter(mAdapter);

                mAdapter.setOnItemClickLitener(new HomeTemplate1Adapter.OnItemClickLitener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        SectionContent content = section.sectionContentList.get(position);
                        if (content.action != null) {
                            content.action.jump(context);
                        }
                    }
                });
                break;
            case 2:
//                ListView picList = ViewHolderUtils.getViewHolderView(convertView,
//                        R.id.template_2_event_layout);
//                picList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                    @Override
//                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//
//                        SectionContent content = section.sectionContentList.get(position);
//                        if (content.action != null) {
//                            content.action.jump(context);
//                        }
////                        Toast.makeText(context,""+ position ,Toast.LENGTH_SHORT).show();
//                    }
//                });

                LinearLayout ll = ViewHolderUtils.getViewHolderView(convertView, R.id.linear_ll);
                ll.removeAllViews();
                LogUtil.i("--------sectionContentList.size--", "" + section
                        .sectionContentList.size());
                for (int i = 0; i < section
                        .sectionContentList.size(); i++) {

                    final LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT
                            , LinearLayout.LayoutParams.WRAP_CONTENT);
                    params1.height = 15;
                    View view = new View(context);
                    view.setBackgroundColor(Color.parseColor("#fefefe"));
                    view.setLayoutParams(params1);
                    content = section.sectionContentList.get(i);

                    final ImageView image = new ImageView(context);
//                    image.setImageResource(R.drawable.default_16_9);
                    final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT
                            , LinearLayout.LayoutParams.WRAP_CONTENT);


                    ImageLoader imageLoader = ImageLoader.getInstance();

                    ll.addView(image);
                    ll.addView(view);
                    imageLoader.loadImage(content.img, new SimpleImageLoadingListener() {
                        @Override
                        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                            // Do whatever you want with Bitmap

                            LogUtil.i("--------sectionContentList.img--", loadedImage.getHeight()
                                    + "  " + loadedImage.getWidth());

                            params.width = DisplayUtil.getScreenWidth();
                            params.height = DisplayUtil.getScreenWidth() * loadedImage.getHeight() / loadedImage.getWidth();

                            image.setLayoutParams(params);
//                            image.setImageBitmap(loadedImage);

                        }
                    });
                    Glide.with(context).load(content.img).placeholder(R
                            .drawable.default_16_9).error(R
                            .drawable.default_16_9).animate(R.anim.abc_fade_in).into(image);

                    image.setTag("" + i);
                    image.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            SectionContent content = section.sectionContentList.get(
                                    Integer.parseInt(image.getTag().toString()));
                            if (content.action != null) {
                                content.action.jump(context);
                            }
                        }
                    });


                    if (i == section
                            .sectionContentList.size() - 1) {
                        EventBus.getDefault().post(new ListViewHightEvent(true));
                    }
                }


//                PicListAdapter picListAdapter = new PicListAdapter(context, section
//                        .sectionContentList);
//                picList.setAdapter(picListAdapter);
//                ListViewUtility.setListViewHeightBasedOnChildren(picList);
                break;
            case 3:
                RecyclerView horizontalView3 = ViewHolderUtils.getViewHolderView
                        (convertView, R.id.recyclerview_horizontal);
                horizontalView3.setLayoutManager(linearLayoutManager);
                //设置适配器
                HomeTemplate3Adapter adapter3 = new HomeTemplate3Adapter(context,
                        section.sectionContentList);
                horizontalView3.setAdapter(adapter3);
                adapter3.setOnItemClickLitener(new HomeTemplate3Adapter.OnItemClickLitener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        SectionContent content = section.sectionContentList.get(position);
                        if (content.action != null) {
                            content.action.jump(context);
                        }
                    }
                });
                break;
            case 4:
                RecyclerView horizontalView4 = ViewHolderUtils.getViewHolderView
                        (convertView, R.id.recyclerview_horizontal);
                final GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 2);
                gridLayoutManager.setOrientation(GridLayoutManager.HORIZONTAL);
                horizontalView4.setLayoutManager(gridLayoutManager);
                //Top 1
                if (section.sectionContentList.size() == 0) {
                    break;
                }
                View header = LayoutInflater.from(context).inflate(
                        R.layout.item_template_4_header, horizontalView4, false);
                header.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        section.sectionContentList.get(0).action.jump(context);
                    }
                });
                ImageView image = (ImageView) header.findViewById(R.id.top_1_image);
                TextView name = (TextView) header.findViewById(R.id.top_1_name);
                Glide.with(context).load(section.sectionContentList.get(0).img).placeholder(R.drawable
                        .default_avatar_square).error(R.drawable.default_avatar_square).animate(R.anim
                        .abc_fade_in).into(image);
                name.setText(section.sectionContentList.get(0).name);
                final HomeTemplate4Adapter adapter4 = new HomeTemplate4Adapter(header, context, section
                        .sectionContentList.subList(1, section.sectionContentList.size()));
                horizontalView4.setAdapter(adapter4);
                gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                    @Override
                    public int getSpanSize(int position) {
                        return adapter4.isHeader(position) ? gridLayoutManager.getSpanCount()
                                : 1;
                    }
                });
                break;
        }
        if (position == sectionList.size() - 1) {
            EventBus.getDefault().post(new ListViewHightEvent(true));
        }

        return convertView;
    }

    SectionContent content;
    ImageView image;

    class PicListAdapter extends BaseAdapter {
        List<SectionContent> mList;
        Context context;

        public PicListAdapter(Context context, List<SectionContent> sectionContentList) {
            mList = sectionContentList;
            this.context = context;
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(context, R.layout.item_template_event_image, null);
            }
            final ImageView image = (ImageView) convertView.findViewById(R.id.event_image);
            final SectionContent content = mList.get(position);
            Glide.with(context).load(content.img).placeholder(R.drawable
                    .default_16_9).error(R.drawable.default_16_9).animate(R.anim
                    .abc_fade_in).into(image);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    BitmapFactory.Options opts = new BitmapFactory.Options();
                    opts.inJustDecodeBounds = true;
                    opts.inSampleSize = 1;
                    opts.inJustDecodeBounds = false;
                    Drawable drawable = loadImageFromNetwork(content.img);
                    LogUtil.i("-----drawable---", "" + DisplayUtil.getScreenWidth() + "  "
                            + DisplayUtil.getScreenWidth() * drawable.getMinimumWidth() / drawable.getMinimumHeight());
//                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DisplayUtil.getScreenWidth()
//                            , DisplayUtil.getScreenWidth() * drawable.getMinimumWidth() / drawable.getMinimumHeight());
//                    image.setLayoutParams(params);

                }

            }).start();

            return convertView;

        }


        private Drawable loadImageFromNetwork(String imageUrl) {
            Drawable drawable = null;
            try {
                // 可以在这里通过文件名来判断，是否本地有此图片
                drawable = Drawable.createFromStream(
                        new URL(imageUrl).openStream(), "image.jpg");
            } catch (IOException e) {
                Log.d("test", e.getMessage());
            }
            if (drawable == null) {
                Log.d("test", "null drawable");
            } else {
                Log.d("test", "not null drawable");
            }

            return drawable;
        }
    }


}
